package com.yxuan.springboot.controller;

import com.yxuan.springboot.model.TestTypeDetails;
import com.yxuan.springboot.service.TestTypeDetailsService;
import com.yxuan.springboot.util.COSImage;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import static javafx.scene.input.KeyCode.O;

/**
 * @author zchao
 * TestTypeDetails控制器
 * @date 2023-05-16 14:22:56
 */
@Controller
@Slf4j
@Api(tags = "")
@RequestMapping(value = "/testtypedetails", method = {RequestMethod.POST, RequestMethod.GET})
public class TestTypeDetailsController extends BaseController<TestTypeDetails> {

    @Autowired
    private TestTypeDetailsService testTypeDetailsService;

    //测试首页
    @ResponseBody
    @RequestMapping(value = "/testhome", method = RequestMethod.GET)
    public HashMap<String, Object> testHome() throws Exception {
        return testTypeDetailsService.testHome();
    }

    //    查询所有测试类型
    @Override
    @RequestMapping(value = "/alltype", method = RequestMethod.GET)
    public List<TestTypeDetails> loadAll() {
        return super.loadAll();
    }

    //    TODO 添加测试类型,只管添加就行
    @Override
    @RequestMapping(value = "/addtype", method = RequestMethod.POST)
    public String saveT(TestTypeDetails entity) throws IOException {
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        entity.setCreateTime(timestamp);
        entity.setUpdateTime(timestamp);
        entity.setJoinNum(0);
        entity.setHot("0");
        return super.saveT(entity);
    }

    //    删除测试类型
    @Override
    @RequestMapping(value = "/deltype", method = RequestMethod.POST)
    public String delete(@RequestBody TestTypeDetails testTypeDetails) {
        return super.delete(testTypeDetails);
    }

    //   TODO 修改测试类型，看是否修改图片，若修改，则看之前是否存在图片，若存在，则删除原本的图片，再添加新的；
//              若之前不存在图片，则直接添加。
    @Override
    @RequestMapping(value = "/updatetype", method = RequestMethod.POST)
    public String updT(TestTypeDetails entity) throws Exception {
        //         1.是否修改图片
        if (entity.getPic() != null) {

            TestTypeDetails tById = testTypeDetailsService.findTById(String.valueOf(entity.getId()));
//            之前有图片
            if(tById.getPic() != null){
                //                删除原本存储在腾讯云的图片
//                获取文件名
                String url = tById.getPic();
                URL url1 = new URL(url);
                String path = url1.getPath();
                String substring = path.substring(path.lastIndexOf('/') + 1);
                COSImage cosImage = new COSImage();
//                url = "腾讯云文件夹名+文件名"
                String url2 = "zypic/" + substring;
                cosImage.deleteFile(url2);
            }
        }
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        entity.setUpdateTime(timestamp);
        return super.updT(entity);
    }


//  测试详情界面
    @ResponseBody
    @RequestMapping(value = "/testdetils",method = RequestMethod.POST)
    public HashMap<String,Object> prepareTest(@RequestBody TestTypeDetails testTypeDetails) throws Exception {
        return testTypeDetailsService.prepareTest(testTypeDetails.getId());
    }


//    上传图片（仅jpg和png）

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file)  {
//        获取上传文件信息
        try{
            if (file != null){
                String filename;
                String originalFilename = file.getOriginalFilename();
                String contentType = file.getContentType();
                long size = file.getSize();
                String localPath = System.getProperty("user.dir") + "/src/main/resources/img/type";
//        根据文件名获取文件后缀名
                String substring = originalFilename.substring(originalFilename.lastIndexOf('.'));
                //            只允许上传图片，若上传非图片，提醒上传图片
                if (!substring.equals("png") && !substring.equals("jpg")) {
                    return ERROR;
                }
//            得到文件名
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                filename = uuid + "." + substring;
                COSImage cosImage = new COSImage();
//            文件保存路径
                file.transferTo(new File(new File(localPath).getAbsolutePath() + "/" + filename));
                String localFilePath = System.getProperty("user.dir") + "/src/main/resources/img/type/" + filename;
//            将保存在本地的头像上传到腾讯云-对象存储
                cosImage.onLoad_img(filename, localFilePath);
//            }
//        获取头像的网址
            String http = "https://resource-1316563429.cos.ap-nanjing.myqcloud.com/zypic/" + filename;
                //        执行完毕，删除本地文件
                File localfile = new File(localFilePath);
                localfile.delete();
                return http;
        }
//            上传文件为空，
            return null;
        }catch (Exception e){
                log.error(e.getMessage());
                return ERROR;
            }
    }
}
